package com.panda.utils;

import com.panda.pojo.Context;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*

    解析碎片

 */
 class FragmentUtils {

    private static Pattern pattern = Pattern.compile("(?<=\n|^) *Fragment");


    //提取碎片
     static String extract(Context context, String text) {

        Map<String, String> fragments = context.getFragments();

        String t = text;

        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {

            int param = Finder.findParam(text.toCharArray(), matcher.end());

            if (param == -1) {
                throw new RuntimeException("必须指定碎片id:" + text.substring(matcher.start()));
            }

            String ps = text.substring(matcher.end(), param).trim();

            //碎片id
            ps = ps.substring(1, ps.length() - 1);

            int body = Finder.findBody(text.toCharArray(), param);

            if (body == -1) {
                throw new RuntimeException("没有碎片体:" + text.substring(matcher.start()));
            }

            String bs = text.substring(param, body).trim();

            bs = bs.substring(1, bs.length() - 1);

            String put = fragments.put(ps, bs);

            if (put != null) {
                throw new RuntimeException("重复的碎片,请使用其他id: " + ps);
            }

            t = t.replace(text.substring(matcher.start(), body), "");

        }

        return t;

    }



}
